import Chance from 'chance'
import CSS from 'csstype'

const chance = new Chance()

export function randomStr():string{
    return chance.string({length:6,alpha: true})
}

export function sizeStyle(width?:number|string,height?:number|string):CSS.Properties{
    const style:CSS.Properties = {}
    if(width){
        if(typeof width==='number'){
            width = width>0?`${width}px`:""
        }
        style.width = width;
    }
    if(height){
        if(typeof height==='number'){
            height = height>0?`${height}px`:""
        }
        style.width = height
    }
    
    return style
}

export function getBase64Url(file:File):Promise<string>{
    const reader = new FileReader()

    return new Promise((resolve,reject)=>{
        reader.addEventListener('load',()=>{
            resolve(reader.result as string || "")
        },false)
    
        reader.addEventListener('error',()=>{
            reject(reader.error)
        })
        reader.readAsDataURL(file)
    })
}

export function style(ele:HTMLElement,style:CSS.Properties,replace:boolean=true):void{
    if(replace){
        ele.setAttribute('style',"")
    }
    Object.entries(style).forEach(([name,val]:[any,any])=>{
        ele.style[name] = val
    })
}

export function getNumberfilterString(str:string,isFloat:boolean=false):number{
    str = str.replace(/[^0-9\.]/ig,'') || "0"
    if(isFloat){
        return parseFloat(str)
    }
    return parseInt(str)
}